<script lang="ts" setup>
// 导入数据
import {
  CusBtn,
  DoctorCard,
  DoctorItem,
  List,
  ListItem,
  Tabs,
  TabsItem
} from '@/components/business/tkmgr/tpbase/index'
import { useRouter } from 'vue-router'
import {SkeletonList} from "@/components/basic/Loading"
import to from '@/utils/awaitTo'
import { computed, provide, reactive, ref, toRefs } from 'vue'
import { ControlsCard, PaginationCard, SearchCard } from '@/components/basic/Card'
import { Pagination } from '@/components/basic/Pagination'
import Api from '@/api/'
import { Group } from '@/components/basic/Loading'
import { UploadImage } from '@/components/basic/Upload'
import { message } from 'ant-design-vue'

// 实例
const router = useRouter()


// 响应式数据
const firstList = ref<API.FirstTopicInfo[]>([]) // 列表数据
const secondList = ref([])
const thirdList = ref([])
const allList = ref([{ id: '', name: '全部', allowIdentifiers: 3 }])

/** 一级分类方法 */
const firstParams = reactive({  // 一级分类参数
  pageNum: 1,
  pageSize: 100000
})
const activeOne = ref('')
const getFirstList = async () => {
  const [err, data] = await to(Api.tpbase.topicFirst(firstParams))
  if (!err) {
    firstList.value = allList.value.concat(data)
  }
}
const handleLevelOne = (item: API.FirstTopicInfo) => {
  // console.log(item)
  activeOne.value = item.id

  secondList.value = []
  thirdList.value = []
  activeTwo.value = ''
  activeThree.value = ''
  queryParams.firstClassificationIds = item.id ? [item.id] : []
  queryParams.firstClassificationName = item.name
  queryParams.secondClassificationIds = []
  queryParams.secondClassificationName = ''
  queryParams.thirdClassificationIds = []
  queryParams.thirdClassificationName = ''

  form.value.firstClassificationId = item.id
  form.value.firstClassificationName = item.name
  form.value.secondClassificationId = ''
  form.value.secondClassificationName = ''
  form.value.thirdClassificationId = ''
  form.value.thirdClassificationName = ''

  getSecondList(item.id)
  getList()
  getAccordDepEchoDoctor({ classificationId: item.id })  //根据科室回显医生
}
// 选择科室form 切换
const handleDepartmentChange = async (sid: string) => {
  await getSecondList(sid)
  // 过滤
  const [data] = firstList.value.filter((item) => item.id === sid)
  form.value.firstClassificationId = data.id
  form.value.firstClassificationName = data.name
  form.value.secondClassificationId = ''
  form.value.secondClassificationName = ''
  form.value.thirdClassificationId = ''
  form.value.thirdClassificationName = ''
}

/** 字母 */
const activeLetter = ref('')
const handleLevelLetter = (item: API.DefaultInfo) => {
  activeLetter.value = item.value
}

/** 二级分类方法 */
const secondParams = reactive({
  pageNum: 1,
  pageSize: 100000,
  parentIds: [],
  queryS: [],
  reasonable: false
})
const activeTwo = ref('')
const getSecondList = async (id: string) => {
  secondParams.parentIds = [id]
  const [err, data] = await to(Api.tpbase.topicSecond(secondParams))
  if (!err) {
    secondList.value = data.rows
  }
}
const handleLevelTwo = (item: API.FirstTopicInfo) => {
  activeTwo.value = item.id
  thirdList.value = []
  activeThree.value = ''
  queryParams.secondClassificationIds = [item.id]
  queryParams.secondClassificationName = item.name
  queryParams.thirdClassificationIds = []
  queryParams.thirdClassificationName = ''

  form.value.secondClassificationId = item.id
  form.value.secondClassificationName = item.name
  form.value.thirdClassificationId = ''
  form.value.thirdClassificationName = ''
  getThirdList(item.id)
  getList()
}

// 选择病重form 切换
const handleDiseaseChange = async (sid: string) => {
  await getThirdList(sid)
  // 过滤
  const [data] = secondList.value.filter((item) => item.id === sid)

  form.value.secondClassificationId = data.id
  form.value.secondClassificationName = data.name
  form.value.thirdClassificationId = ''
  form.value.thirdClassificationName = ''
}

/** 三级分类方法 */
const thirdParams = reactive({
  pageNum: 1,
  pageSize: 100000,
  parentIds: [],
  queryS: [],
  reasonable: false
})
const activeThree = ref('')
const getThirdList = async (id: string) => {
  thirdParams.parentIds = [id]
  const [err, data] = await to(Api.tpbase.topicSecond(thirdParams))
  if (!err) {
    console.log(data)
    thirdList.value = data.rows
  }
}
const handleLevelThree = (item: API.FirstTopicInfo) => {
  activeThree.value = item.id
  queryParams.thirdClassificationIds = [item.id]
  queryParams.thirdClassificationName = item.name

  form.value.thirdClassificationId = item.id
  form.value.thirdClassificationName = item.name
  getList()
}

// 选择症状form 切换
const handleSymptomChange = (sid: string) => {
  // 过滤
  const [data] = thirdList.value.filter((item) => item.id === sid)
  console.log(data)
  form.value.thirdClassificationId = data.id
  form.value.thirdClassificationName = data.name
}


// 数据列表
const queryRef = ref()
const formRef = ref()
const queryParams = reactive({
  createBy: '',
  doctorId: '',
  firstClassificationIds: [],
  firstClassificationName: '',
  keyword: '',
  keywordKeyword: '',
  pageDTO: {
    columns: [],
    orders: [],
    pageNum: 1,
    pageSize: 10
  },
  pageNum: 1,
  pageSize: 1,
  queryS: [],
  querySName: '',
  secondClassificationIds: [],
  secondClassificationName: '',
  thirdClassificationIds: [],
  thirdClassificationName: ''
})
const list = ref([])
const loading = ref(false)
const error = ref()
const total = ref(0)

// 响应式数据
const state = reactive({
  open: false,
  title: '',
  rules: {
    firstClassificationId: [
      {
        required: true,
        message: `一级分类不能为空`,
        trigger: ['blur', 'change']
      }
    ],
    secondClassificationId: [
      {
        required: true,
        message: `二级分类不能为空`,
        trigger: ['blur', 'change']
      }
    ],
    // thirdClassificationId:[
    //   {
    //     required: true,
    //     message: `三级分类不能为空`,
    //     trigger: ['blur', 'change']
    //   }
    // ],
    topicTitle: [ //话题
      {
        required: true,
        message: `话题内容不能为空`,
        trigger: ['blur', 'change']
      }
    ],

    insertDataSource: [ //话题来源
      {
        required: true,
        message: `话题来源不能空`,
        trigger: ['blur', 'change']
      }
    ]

    // sourceImageUrl: [
    //     {
    //         required: true,
    //         message: "话题来源图片不能为空",
    //         trigger: ['blur', 'change']
    //     }
    // ],

    // topicHyperlink: [ //话题超链接
    //     {
    //         required: true,
    //         // message: `超链接不能为空`,
    //         trigger: ['blur', 'change'],
    //         validator: (_rule: string, value: string) => {
    //             // 如果已经有一个计时器在运行，清除它
    //             if (timeoutId) {
    //                 clearTimeout(timeoutId);
    //             }
    //             // 返回一个新的 Promise
    //             return new Promise<void>((resolve, reject) => {
    //                 // 设置一个新的计时器
    //                 timeoutId = setTimeout(() => {
    //                     if (!value) {
    //                         reject(`超链接不能为空`);
    //                     } else if (!isUrlReg.test(value)) {
    //                         reject(`超链接格式不正确`);
    //                     } else {
    //                         resolve();
    //                     }
    //                 }, 500); // 500ms 的节流时间
    //             });
    //         },
    //         whitespace: true,
    //     }
    // ],

    // topicContentDataSource: [ //内容来源
    //     {
    //         required: true,
    //         message: "内容来源不能为空",
    //         trigger: ['blur', 'change']
    //     }
    // ],

    // topicContent: [
    //     {
    //         required: true,
    //         message: `内容不能为空`,
    //         trigger: ['blur', 'change']
    //     }
    // ]
  },
  sendLoading: false,
  form: {
    firstClassificationId: undefined,
    firstClassificationName: '',
    secondClassificationId: undefined,
    secondClassificationName: '',
    thirdClassificationId: undefined,
    thirdClassificationName: ''
  } as any,
  doctorList: [] // 医生列表
})

const { open, title, form, rules, sendLoading, doctorList } = toRefs(state)

// 添加话题
const handleAddTopic = () => {
  sendLoading.value = true
  reset()

  setTimeout(() => {
    open.value = true
    title.value = '新增话题'
    sendLoading.value = false
    form.value = Object.assign({}, form.value, { status: 1 })
  }, 200)
}

// 提交事件
const handleSubmitOk = (formEl) => {
  if (!formEl) return
  formEl.validate().then(async (values) => {
    const params = Object.assign({}, form.value, values)

    // 修改话题
    if (params.status == 2) {
      const paramsInfo = {
        firstClassificationId: params.firstClassificationId,
        secondClassificationId: params.secondClassificationId,
        thirdClassificationId: params.thirdClassificationId,
        topicId: params.topicId,
        topicTitle: params.topicTitle
      }

      const [error, data] = await to(Api.tpbase.topicUpdateTopic(paramsInfo))
      if (!error && data === 1) {
        open.value = false
        message.success('修改成功')

        setTimeout(() => {
          getList()
        }, 3000)
      }

    }

    // 新增
    else {
      const [error] = await to(Api.tpbase.topicInsert(params))
      if (!error) {
        open.value = false
        message.success('新增成功,等待审核过审')
      }
    }
  })
}

/** 操作事件 */
const handleMenus = ({ c, b }) => {
  switch (c.key) {
    case 'edit': // 修改
      getTopicEdit(b)
      break
    case 'view': // 查看
      goPageListItem(b)
      break
  }
}

// 跳转话题内容事件
const goPageListItem = (item) => {
  let routeUrl = router.resolve({
    path: '/content',
    query: {
      topicId: item.topicId,
      topicTitle: item.topicTitle
    }
  })
  window.open(routeUrl.href, '_blank')
}


// 修改标题事件
const getTopicEdit = async (item) => {
  console.log(item)
  // 一级分类
  await getFirstList()
  // 二级分类
  await getSecondList(item.firstClassificationId)
  // 三级分类
  await getThirdList(item.secondClassificationId)
  // 标题
  title.value = item.topicTitle
  form.value = { ...item, status: 2 }
  open.value = true
}


// 搜索列表
const getList = async () => {
  loading.value = true
  const [err, data] = await to(Api.tpbase.topicList(queryParams))
  loading.value = false
  if (err) return error.value = err
  // console.log(data)
  list.value = data.list
  total.value = Number(data.total)
}


// 根据科室回显医生
const getAccordDepEchoDoctor = async (item) => {
  if (item.classificationId) {
    const [error, data] = await to(Api.tpbase.topicEchoDoctor({ ...item, searchName: '' }))
    if (!error) {
      doctorList.value = data
    }
  } else {
    doctorList.value = []
  }

}

// 搜索事件
const handleQuery = () => {
  getList()
}

// 重置
const handleReset = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  getList()
}

// 重置表单
const reset = () => {
  form.value = {
    ...form.value,
    topicTitle: '',
    insertDataSource: '',
    sourceImageUrl: '',
    topicHyperlink: '',
    topicContentDataSource: '0',
    topicContent: '',
    topicId: '',
    status: 0
  }
}


// 是否可以新增
const isAdd = computed(() => {
  return !(form.value.firstClassificationId && form.value.secondClassificationId)
})

// 新增话题显示计算
const addTopicShow = computed(() => {
  return Number(form.value.status) === 1
})

// 修改话题显示计算
const editTopicShow = computed(() => {
  return Number(form.value.status) === 2
})


//内容来源不同选择不同的字体
const contentTips = computed(() => {
  switch (form.value.topicContentDataSource) {
    case '0':
      return `chatGpt自动生成改内容不必填写`
    case '1':
      return `请输入文字内容`
    case '2':
      return `复制粘贴到该内容里`
    case '3':
      return `输入适量的内容，会结合chatgpt智能合并`
    default:
      return `what?...`
  }
})

// 字母字典
const letterList = ref([
  {
    label: 'A',
    value: 'A'
  },
  {
    label: 'B',
    value: 'B'
  },
  {
    label: 'C',
    value: 'C'
  },
  {
    label: 'D',
    value: 'D'
  },
  {
    label: 'E',
    value: 'E'
  },
  {
    label: 'F',
    value: 'F'
  },
  {
    label: 'G',
    value: 'G'
  },
  {
    label: 'H',
    value: 'H'
  },
  {
    label: 'I',
    value: 'I'
  },
  {
    label: 'J',
    value: 'J'
  },
  {
    label: 'K',
    value: 'K'
  },
  {
    label: 'L',
    value: 'L'
  },
  {
    label: 'M',
    value: 'M'
  },
  {
    label: 'N',
    value: 'N'
  },
  {
    label: 'O',
    value: 'O'
  },
  {
    label: 'P',
    value: 'P'
  },
  {
    label: 'Q',
    value: 'Q'
  },
  {
    label: 'R',
    value: 'R'
  },
  {
    label: 'S',
    value: 'S'
  },
  {
    label: 'T',
    value: 'T'
  },
  {
    label: 'U',
    value: 'U'
  },
  {
    label: 'V',
    value: 'V'
  },
  {
    label: 'W',
    value: 'W'
  },
  {
    label: 'X',
    value: 'X'
  },
  {
    label: 'Y',
    value: 'Y'
  },
  {
    label: 'Z',
    value: 'Z'
  }
])

// 请选择内容来源
const TopicSourceListDist = [
  {
    label: '抖音',
    value: '抖音'
  },
  {
    label: '百度贴吧',
    value: '百度贴吧'
  },
  {
    label: '好大夫',
    value: '好大夫'
  },
  {
    label: '丁香医生',
    value: '丁香医生'
  },
  {
    label: '有来医生',
    value: '有来医生'
  },
  {
    label: '知乎',
    value: '知乎'
  },
  {
    label: '医疗问诊平台',
    value: '医疗问诊平台'
  },
  {
    label: '病友交流网',
    value: '病友交流网'
  },
  {
    label: '巢内网',
    value: '巢内网'
  },
  {
    label: '百度健康',
    value: '百度健康'
  },
  {
    label: '39健康网',
    value: '39健康网'
  },
  {
    label: 'INC神外科普',
    value: 'INC神外科普'
  },
  {
    label: '搜狐',
    value: '搜狐'
  },
  {
    label: '百度-各院主任回答',
    value: '百度-各院主任回答'
  },
  {
    label: '百度学术',
    value: '百度学术'
  },
  {
    label: '宝宝知道',
    value: '宝宝知道'
  },
  {
    label: '用户自创',
    value: '用户自创'
  },
  {
    label: '论坛',
    value: '论坛'
  },
  {
    label: '胶质瘤论坛',
    value: '胶质瘤论坛'
  },
  {
    label: '专科医生推荐',
    value: '专科医生推荐'
  }
]

// 内容来源字典
const ContentSourceListDist = [
  {
    label: 'AI',
    value: '0'
  },
  {
    label: '用户自创',
    value: '1'
  },
  {
    label: '全网医学科普节选',
    value: '2'
  },
  {
    label: 'chatGpt智能聚合',
    value: '3'
  }
]


getFirstList()
getList()
provide('queryParams', queryParams)
</script>

<template>
  <div>
    <div>
      <!--  分类  -->
      <Tabs>
        <TabsItem label="一级分类">
          <CusBtn
            v-for="(item,index) in firstList" :key="index" :active="activeOne"
            :fieldNames="{label:'name',value:'id'}"
            :item="item" class="mr-3 mb-3"
            @click="handleLevelOne"
          />
        </TabsItem>

        <TabsItem v-if="secondList && secondList.length" label="二级分类">
          <CusBtn
            v-for="(item,index) in secondList" :key="index" :active="activeTwo"
            :fieldNames="{label:'name',value:'id'}"
            :item="item" class="mr-3 mb-3"
            @click="handleLevelTwo"
          />
        </TabsItem>

        <TabsItem v-if="thirdList && thirdList.length" label="三级分类">
          <CusBtn
            v-for="(item,index) in thirdList" :key="index" :active="activeThree"
            :fieldNames="{label:'name',value:'id'}"
            :item="item" class="mr-3 mb-3"
            @click="handleLevelThree"
          />
        </TabsItem>
      </Tabs>

      <!-- 搜索 -->
      <SearchCard class="mt-3">
        <a-form ref="queryRef" :model="queryParams" layout="inline">
          <a-form-item label="标题" name="keyword">
            <a-input v-model:value="queryParams.keyword" />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleQuery">搜索</a-button>
            <a-button class="ml-3" @click="handleReset(queryRef)">重置</a-button>
          </a-form-item>
        </a-form>
      </SearchCard>


      <!-- 医生列表 -->
      <DoctorCard v-if="doctorList.length">
        <DoctorItem v-for="(item,index) in doctorList" :key="index" :item="item" />
      </DoctorCard>

      <!-- 操作 -->
      <ControlsCard :size="20" direction="vertical">
        <!-- 第一行 -->
        <a-space :size="30" class="flex">
          <a-space v-if="form.firstClassificationName" class="flex">
            <div class="text-sm font-sans font-normal">一级分类</div>
            <div class="text-xs font-normal">{{ form.firstClassificationName }}</div>
          </a-space>
          <a-space v-if="form.secondClassificationName" class="flex">
            <div class="text-sm font-sans font-normal">二级分类</div>
            <div class="text-xs font-normal">{{ form.secondClassificationName }}</div>
          </a-space>
          <a-space v-if="form.thirdClassificationName" class="flex">
            <div class="text-sm font-sans font-normal">三级分类</div>
            <div class="text-xs font-normal">{{ form.thirdClassificationName }}</div>
          </a-space>
        </a-space>


        <a-button :disabled="false" :loading="sendLoading" block danger shape="default" size="large" type="default"
                  @click="handleAddTopic">
          新增话题
        </a-button>
      </ControlsCard>

      <!--  表格  -->
      <List>
        <Group :error="error" :is-empty="!list.length" :pending="loading">
          <template #loading>
            <SkeletonList />
          </template>

          <ListItem v-for="(item,index) in list" :key="index" :item="item" class="justify-between"
                    @menus="handleMenus" />
        </Group>
      </List>

      <!-- 分页 -->
      <PaginationCard>
        <Pagination v-model:page-num="queryParams.pageDTO.pageNum" v-model:page-size="queryParams.pageDTO.pageSize"
                    :total="total" @pagination="getList" />
      </PaginationCard>
    </div>

    <div>
      <!-- 新增修改 -->
      <a-modal v-model:open="open" :title="title" @ok="handleSubmitOk(formRef)">
        <a-form
          ref="formRef"
          :model="form"
          :rules="rules"
          layout="vertical"
          name="TopicModal"
        >

          <!-- 类型1 选择好  -->
          <a-space :size="30" class="mb-3 flex">
            <a-space v-if="form.firstClassificationName" class="flex">
              <div class="text-sm font-sans font-normal">一级分类</div>
              <div class="text-xs font-normal">{{ form.firstClassificationName }}</div>
            </a-space>
            <a-space v-if="form.secondClassificationName" class="flex">
              <div class="text-sm font-sans font-normal">二级分类</div>
              <div class="text-xs font-normal">{{ form.secondClassificationName }}</div>
            </a-space>
            <a-space v-if="form.thirdClassificationName" class="flex">
              <div class="text-sm font-sans font-normal">三级分类</div>
              <div class="text-xs font-normal">{{ form.thirdClassificationName }}</div>
            </a-space>
          </a-space>

          <!-- 科室 -->
          <a-form-item v-if="editTopicShow || addTopicShow" label="科室" name="firstClassificationId">
            <a-select
              v-model:value="form.firstClassificationId"
              placeholder="请选择科室"
              @change="handleDepartmentChange"

            >
              <a-select-option
                v-for="item in firstList"
                :key="item.id"
                :disabled="item.allowIdentifiers === 3"
                :value="item.id"
              >{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <!-- 病种  -->
          <a-form-item v-if="editTopicShow || addTopicShow" label="病种" name="secondClassificationId">
            <a-select
              v-model:value="form.secondClassificationId"
              placeholder="请选择病种"
              @change="handleDiseaseChange"

            >
              <a-select-option
                v-for="item in secondList"
                :key="item.id"
                :value="item.id"
              >{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <!-- 症状  -->
          <a-form-item v-if="editTopicShow || addTopicShow" label="症状" name="thirdClassificationId">
            <a-select
              v-model:value="form.thirdClassificationId"
              placeholder="请选择症状"
              @change="handleSymptomChange"
            >
              <a-select-option
                v-for="item in thirdList"
                :key="item.id"
                :value="item.id"
              >{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <!-- 话题标题  -->
          <a-form-item v-if="editTopicShow || addTopicShow" :validateFirst="false" label="话题" name="topicTitle">
            <a-textarea
              v-model:value="form.topicTitle"
              show-count
            />
          </a-form-item>

          <!-- 话题来源 -->
          <a-form-item
            v-if="addTopicShow"
            :validateFirst="true"
            label="话题来源"
            name="insertDataSource"
          >
            <a-select
              v-model:value="form.insertDataSource"
              placeholder="请选择内容来源"
            >
              <a-select-option
                v-for="item in TopicSourceListDist"
                :key="item.value"
                :value="item.value"
              >{{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <!-- 话题来源图片-->
          <a-form-item
            v-if="form.insertDataSource !== '用户自创' && addTopicShow"
            :validateFirst="true"
            extra="图片"
            label="话题来源图片"
            name="sourceImageUrl"
          >
            <UploadImage v-model="form.sourceImageUrl" />
          </a-form-item>

          <!-- 话题超链接  -->
          <a-form-item
            v-if="form.insertDataSource !== '用户自创' && addTopicShow"
            extra="例如:https://baike.baidu.com/item/%e6%9d%8e%e7%99%bd/1043"
            has-feedback
            label="话题超链接"
            name="topicHyperlink"
          >
            <a-textarea
              v-model:value="form.topicHyperlink"
              :rows="1"
            />
          </a-form-item>

          <!-- 内容来源 -->
          <a-form-item
            v-if="addTopicShow"
            :validateFirst="true"
            extra="内容来源选择’AI‘ chatgpt自动生成 "
            has-feedback
            label="内容来源"
            name="topicContentDataSource"
          >
            <a-select
              v-model:value="form.topicContentDataSource"
              placeholder="请选择内容来源"
            >
              <a-select-option
                v-for="item in ContentSourceListDist"
                :key="item.value"
                :value="item.value"
              >{{ item.label }}
              </a-select-option
              >
            </a-select>
          </a-form-item>

          <!-- 内容 -->
          <a-form-item
            v-if="Number(form.topicContentDataSource) !== 0 && addTopicShow"
            :extra="contentTips"
            label="内容"
            name="topicContent"
          >
            <a-textarea
              v-model:value="form.topicContent"
              :rows="4"
              placeholder="请输入内容"
              show-count
            />
          </a-form-item>

        </a-form>
      </a-modal>
    </div>
  </div>
</template>

<style lang="less" scoped>
</style>
